<template>
  <div>
    <home/>
    <div class="divmain baseHeight">
      <div style="width: 1000px;height:200px;font-size: 0;">
        <div style="width: 30%;height: 500px;overflow-y:auto">
          <template>
            <a-tree
              :load-data="onLoadData"
              :tree-data.sync="treeData"
              :expandedKeys.sync="expandedKeys"
              @select="selectTree">
              <template #title="{ nid: treeKey, title,leve }">
                <a-dropdown :trigger="['contextmenu']">
                  <span>{{ title }}</span>
                  <template #overlay>
                    <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey,leve)">
                      <a-menu-item v-if="leve < 2" key="1">
                        <a-tag color="#87d068">
                          <a-icon type="plus"/>
                          新增分组
                        </a-tag>
                      </a-menu-item>
                      <a-menu-item v-if="leve > 0" key="2">
                        <a-tag color="#2db7f5">
                          <a-icon type="edit"/>
                          修改
                        </a-tag>
                      </a-menu-item>
                      <a-menu-item v-if="leve > 0" key="3">
                        <a-tag color="#f50">
                          <a-icon type="close"/>
                          删除
                        </a-tag>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </a-tree>
          </template>
        </div>
        <div class="floatRight">
          <template>
            <a-list
              class="demo-loadmore-list"
              item-layout="horizontal"
              :data-source="urlList"
            >
              <a-list-item slot="renderItem" slot-scope="item">
                <a slot="actions">
                  <a-button type="link" @click="delUrlItem(item.item_id)">
                    删除
                  </a-button>
                  <a-tag color="#2db7f5" @click="onCopy(item.item_url)">
                    复制到剪切板
                  </a-tag>
                  <a-tag color="#2db7f5" @click="createWindow(item.item_url)">
                    访问
                  </a-tag>
                </a>
                <a-list-item-meta
                  :description="item.item_url"
                >
                  <a slot="title" href="#">{{ item.item_title }}</a>
                  <a-avatar
                    slot="avatar"
                    :src="item.item_ico"
                  />
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </template>

        </div>
      </div>
      <a-button type="primary" shape="circle" class="floatBut" @click="showVs2">
        +
      </a-button>
      <!--    添加/更新框-->
      <template>
        <div>
          <a-modal v-model="visible" title="添加分组">
            <template slot="footer">
              <a-button key="back" type="danger" @click="handleOk">
                保存
              </a-button>
            </template>
            <template>
              <a-form-model ref="addForm">
                <a-form-model-item has-feedback label="NID" prop="nid" disabled>
                  <a-input v-model="addForm.nid"/>
                </a-form-model-item>
                <a-form-model-item has-feedback label="名称" prop="title">
                  <a-input v-model="addForm.title"/>
                </a-form-model-item>
                <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
                </a-form-model-item>
              </a-form-model>
            </template>
          </a-modal>
        </div>
      </template>

      <!--    添加网址-->
      <template>
        <div>
          <a-modal v-model="visible2" title="添加网址" width="600px">
            <template slot="footer">
              <a-button key="back" type="danger" @click="handleOkItem">
                保存
              </a-button>
            </template>
            <template>
              <a-form-model ref="addUrlForm" layout="inline">
                <a-form-model-item>
                  <img :src="src" height="32px" width="32px"/>
                </a-form-model-item>
                <a-form-model-item has-feedback label="名称" prop="item_title">
                  <a-input v-model="addUrlForm.item_title"/>
                </a-form-model-item>
                <a-form-model-item has-feedback label="网址" prop="item_url">
                  <a-input v-model="addUrlForm.item_url"/>
                </a-form-model-item>
              </a-form-model>
            </template>
          </a-modal>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import {ipcApiRoute} from "@/api/main";
import reqwest from 'reqwest';
import VueClipBoard from 'vue-clipboard2'
import Vue from 'vue'
import Home from "@/views/base/common/home";
Vue.use(VueClipBoard)



const fakeDataUrl = 'https://randomuser.me/api/?results=5&inc=name,gender,email,nat&noinfo';

const treeData = [
  {
    title: '我的收藏夹',
    nid: '0',
    leve: 0,
    children: [],
  },
];
export default {
  components: {Home},
  data() {
    return {
      src: '',
      addUrlForm: {
        nid: '',
        item_title: '',
        item_url: '',
        item_ico: ''
      },
      loadingMore: false,
      showLoadingMore: true,
      data: [],
      addForm: {
        nid: '',
        title: '',
        leve: 0
      },
      visible: false,
      visible2: false,
      treeData,
      expandedKeys: ['0'],
      txt: '',
      urlList: []
    };
  },
  created() {
    this.init()
  },
  mounted() {

    this.getData(res => {
      this.loading = false;
      this.data = res.results;
    });
  },
  methods: {
    onCopy(txt){
      this.$copyText(txt).then(
          e=>{
            console.log('已复制至剪切板：', e);
            this.$message.success("已复制至剪切板")
          },
          e=>{
            console.log('复制失败：', e);
            this.$message.error("复制失败")
          }
      )
    },
    delUrlItem(item) {
      const params = {
        action: 'delUrlItem',
        info: {
          item_id: item
        }
      }
      this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res => {
        console.log('res:', res);
        if (res.result) {
          this.$message.success("删除完成")
          this.getUrlList(this.txt)
          return;
        }
        this.$message.error("删除失败")
      })
    },
    createWindow(item) {
      let param = {
        type: 'web',
        content: item
      }
      this.$ipcInvoke(ipcApiRoute.createWindow, param).then(r => {
        console.log(r);
      })
    },
    urlChange(e) {

      var s = this.addUrlForm.item_url;
      var a = s.indexOf("http"); //7
      if (a === -1) {
        this.$message.error("网址需要带http或https")
        return
      }
      var b = s.indexOf("/", 0); //22
      var c = s.substring(0, b); //'c.biancheng.net'

      const url = new URL(s);
      url.hostname; // => 'example.com'
      var ImgObj = new Image();

      ImgObj.src = c + "//" + url.hostname + "/favicon.ico";
      if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
        this.src = ImgObj.src
      }

    },
    IsExstsFile(yourFileURL) {
      var flag;
      var xmlhttp;
      if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();//其他浏览器
      } else if (window.ActiveXObject) {
        if (!xmlhttp) {
          window.alert("不能创建XMLHttpRequest对象");
          flag = false;
        }
      }
      xmlhttp.open("GET", yourFileURL, false);
      xmlhttp.send();
      if (xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200)
          flag = true;
        else
          flag = false;
      }
      return flag;
    },
    showVs2() {
      if (!this.txt) {
        this.$message.error("请选择一个组")
        return
      }
      this.addUrlForm = {
        nid: '',
        item_title: '',
        item_url: '',
        item_ico: ''
      }
      this.addUrlForm.nid = this.txt
      this.visible2 = true
    },
    getData(callback) {
      reqwest({
        url: fakeDataUrl,
        type: 'json',
        method: 'get',
        contentType: 'application/json',
        success: res => {
          callback(res);
        },
      });
    },
    onLoadMore() {
      this.loadingMore = true;
      this.getData(res => {
        this.data = this.data.concat(res.results);
        this.loadingMore = false;
        this.$nextTick(() => {
          window.dispatchEvent(new Event('resize'));
        });
      });
    },
    selectTree(selectedKeys, info) {
      this.txt = info.selectedNodes[0].data.props.dataRef.nid
      this.getUrlList(this.txt)
    },
    getUrlList(nid) {
      const params = {
        action: 'getUrlItem',
        info: {
          nid: nid
        }
      }
      this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res => {
        console.log('res:', res);
        if (res.result.length > 0) {
          this.urlList = res.result
          return;
        }
        this.urlList = []
      })
    },
    confirm() {
      const self = this;
      self.message.info('Clicked on Yes.');
    },
    init() {
      const self = this;
      const params = {
        action: 'get',
        info: {
          nid: '0'
        }
      }
      this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res => {
        console.log('res:', res);
        if (res.result.length == 0) {
          self.$message.error(`没有数据`);
          return;
        }
        const ress = res.result;
        for (let i = 0; i < ress.length; i++) {//第一层
          const params = {
            action: 'getTreeOfPid',
            info: {
              pid: ress[i].nid
            }
          }
          this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res2 => {
            console.log('res2:', res2);
            const lv2 = res2.result;
            if (lv2.length > 0) {
              for (let j = 0; j < lv2.length; j++) {
                const params = {
                  action: 'getTreeOfPid',
                  info: {
                    pid: lv2[j].nid
                  }
                }
                this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res3 => {
                  console.log('res3:', res3);
                  if (res3.result) {
                    lv2[j].children = res3.result
                  } else {
                    lv2[j].children = []
                  }
                })
              }
            }
            ress[i].children = lv2
            this.treeData = ress
            console.log(this.treeData)
          })
        }
        self.$message.success(`加载完成`);
      })
    },
    getTrr(tree) {
      for (let i = 0; i < tree.length; i++) {
        const params = {
          action: 'getTreeOfPid',
          info: {
            pid: tree[i].nid
          }
        }
        this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res => {
          console.log('res:', res);
          if (res.result) {
            tree[i].children = this.getTrr(res.result)
          } else {
            tree[i].children = []
          }
        })

      }
      return tree
    },
    getGroup(pid) {
      const self = this;
      const params = {
        action: 'getTreeOfPid',
        info: {
          pid: pid
        }
      }
      this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res => {
        console.log('res:', res);
        return res.result;
      })
    },
    showModal() {
      this.visible = true;
    },
    handleOk(e) {
      console.log(e);
      let addForm = this.addForm;
      if (!addForm.nid) {
        self.$message.error(`没有需要添加的数据`);
        return;
      }
      const self = this;
      const params = {
        action: 'addGroup',
        info: {
          ...addForm,
          memo: '-'
        }
      }
      this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res => {
        console.log('res:', res);
        if (res.result) {
          self.$message.success(`添加完成`);
          this.visible = false;
          this.init()
          return;
        }
        self.$message.error(`添加失败`);
      })

    },
    handleOkItem(e) {
      console.log(e);
      let addUrlForm = this.addUrlForm;
      if (!addUrlForm.nid) {
        self.$message.error(`请先选择组`);
        return;
      }
      const self = this;
      const params = {
        action: 'addUrlitem',
        info: {
          ...addUrlForm,
          item_ico: this.src
        }
      }
      this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res => {
        console.log('res:', res);
        if (res.result) {
          self.$message.success(`添加完成`);
          this.visible2 = false;
          this.getUrlList(this.txt)
          return;
        }
        self.$message.error(`添加失败`);
      })

    },
    onContextMenuClick(treeKey, menuKey, leve) {

      console.log(`treeKey: ${treeKey}, menuKey: ${menuKey}`);
      if (menuKey === '1') {
        this.addForm = {nid: '', title: ''}
        this.addForm.nid = this.$baseUtil.uuid()
        this.addForm.pid = treeKey
        this.addForm.leve = leve + 1
        this.showModal()
      }
      if (menuKey === '3') {
        this.deleGroup(treeKey)
      }
    },
    deleGroup(nid) {
      const self = this;
      const params = {
        action: 'delGroup',
        info: {
          nid: nid
        }
      }
      this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res => {
        console.log('res:', res);
        if (res.result) {
          self.$message.success(`删除完成`);
          this.init()
          return;
        }
        self.$message.error(`删除失败`);
      })
    },
    // 获取当前节点id以及下面所有子孙节点的id
    getNodeAndChildrenIds(data) {
      let temp = [];
      const loop = (data) => {
        data.map(item => {
          temp.push(item.id)
          if (item.children && item.children.length) {
            loop(item.children);
          }
        })
      }
      loop(data);
      return temp;
    },
// 更新树组件的数据

    updateTreeData(id) {
      // eslint-disable-next-line no-undef
      const temp = _.cloneDeep(this.treeData);
      let node;
      const loopFn = (data, id) => {
        if (node) {
          return;
        }
        data.some((item) => {
          if (item.id === id) {
            // eslint-disable-next-line no-undef
            node = _.cloneDeep(item.children);
            item.children = [];
            return true;
          }
          if (item.children && item.children.length) {
            loopFn(item.children, id);
          }
        });
      };
      // 获取A节点的子节点,并把A节点的children移除
      loopFn(temp, id);
      // eslint-disable-next-line no-undef
      this.treeData = _.cloneDeep(temp);
      // 获取A节点下面所有子孙节点的id
      const nodeIds = this.getNodeAndChildrenIds(node);
      // loadedKeys中移除A节点的key
      // eslint-disable-next-line no-undef
      let loadedKeys = _.cloneDeep(this.loadedKeys.filter(item => item !== id));
      // 去掉A下面已加载的子孙节点的key
      // eslint-disable-next-line no-undef
      loadedKeys = _.cloneDeep(loadedKeys.filter(item => !nodeIds.includes(item)));
      // eslint-disable-next-line no-undef
      this.loadedKeys = _.cloneDeep(loadedKeys);
      // 去掉A下面已展开的子孙节点id
      // eslint-disable-next-line no-undef
      this.expandedKeys = _.cloneDeep(this.expandedKeys.filter(item =>
          !nodeIds.includes(item)));
    },
    onLoadData(treeNode) {

      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve();
          return;
        }
        setTimeout(() => {
          const params = {
            action: 'getTreeOfPid',
            info: {
              pid: treeNode.dataRef.nid
            }
          }
          this.$ipcInvoke(ipcApiRoute.favoriteUrlOperation, params).then(res => {
            console.log('res:', res);
            treeNode.dataRef.children = res.result;
            this.treeData = [...this.treeData];
            resolve();
          })
          // const  tree =  this.getGroup(treeNode.dataRef.nid)
          //  this.treeData = tree
          //  treeNode.dataRef.children = []
          //  for (let i = 0; i < tree.length ;i++) {
          //    treeNode.dataRef.children.push(tree[i])
          //  }
          // treeNode.dataRef.children = this.getGroup(treeNode.dataRef.nid)
          // treeNode.dataRef.children = [
          //   {title: 'Child Node', key: `${treeNode.eventKey}-0`},
          //   {title: 'Child Node', key: `${treeNode.eventKey}-1`},
          // ];

        }, 1000);
      });
    },
  },
};
</script>

<style>
.divmain {
  background-image: linear-gradient(174.2deg, rgba(255, 244, 228, 1) 7.1%, rgba(240, 246, 238, 1) 67.4%);
  height: 100%;
  text-align: left;
  scrollbar-width: none;
}

.floatRight {
  width: 55%;
  border: 2px solid #efeeee;
  height: 90%;
  top: 2rem;
  position: absolute;
  z-index: 9;
  left: 33rem;
  border-radius: 1rem;
  overflow-x: hidden;
  overflow-y: scroll;
}

.floatBut {
  position: absolute;
  z-index: 2147483647;
  right: 1rem;
  bottom: 2rem;
}
</style>
